<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-07-30 20:02:30
 * @LastEditTime: 2020-03-24 17:29:40
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport"
			content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title>Hello APP</title>
		<link rel="stylesheet" type="text/css" href="../css/vant.css">
		<link rel="stylesheet" type="text/css" href="../css/base.css" />
		<link rel="stylesheet" type="text/css" href="../css/local.css" />
		<script type="text/javascript" src="../script/jquery.js"></script>
		<script type="text/javascript" src="../script/layer/mobile/layer.js"></script>
		<script type="text/javascript" src="../script/vue.min.js"></script>
		<script src="../script/vant.min.js"></script>
		<script type="text/javascript" src="../script/fastclick.js"></script>
		<script type="text/javascript" src="../script/base.js"></script>
		<style type="text/css">
			.pd {
				padding: 10px;
			}

			.address {
				overflow: hidden;
				border-radius: 8px;
				padding: 10px 0 10px 10px;
				background: #fff;
				margin-bottom: 10px;
			}

			.van-nav-bar {
				background-color: #51d0d0 !important;
				height: initial !important;
			}

			.van-nav-bar .van-icon {
				color: #fff !important;
			}

			.van-nav-bar__title {
				color: #fff !important;
			}

			.a-c {
				float: left;
				width: 50px;
				height: 80px;
				line-height: 70px;
				text-align: center;
			}

			.a-c img {
				width: 28px;
				text-align: center;
			}

			.a-i {
				float: left;
				width: calc(100% - 50px);
			}

			.shop {
				overflow: hidden;
				border-radius: 8px;
				padding: 10px;
				background: #fff;
				margin-bottom: 10px;
			}

			.row {
				position: relative;
				padding-bottom: 10px;
			}

			.row .img {
				width: 100px;
				height: 80px;
				border-radius: 4px;
				overflow: hidden;
				/* padding: 0 10px; */
			}

			.row .img img {
				width: 100%;
				height: 100%;
			}

			.row .desc {
				padding-right: 5px;
				padding-left: 10px;
			}

			.row .desc .title {
				font-size: 14px;
				line-height: 20px;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}

			.row .desc .title .hot {
				color: #fff;
				background: #cd1b21;
				font-size: 12px;
				border-radius: 2px;
				margin-right: 5px;
				vertical-align: middle;
			}

			.row .desc .sub-title {
				font-size: 12px;
				color: #969799;
				line-height: 20px;
				height: 40px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.row .desc .sub-title * {
				vertical-align: middle;
			}

			.sku {
				padding: 3px 0;
				font-size: 13px;
				color: #9e9e9e;
			}

			.price {
				text-align: right;
				font-size: 14px;
				line-height: initial;
			}

			.red .van-action-sheet__subname {
				color: #cd1b21;
			}

			.van-radio-group {
				display: -webkit-box;
				display: -webkit-flex;
				display: flex;
				-webkit-box-align: center;
				-webkit-align-items: center;
				align-items: center;
				overflow: hidden;
				cursor: pointer;
				-webkit-user-select: none;
				user-select: none;
			}

			.van-radio {
				margin-right: 12px;
			}

			.g {
				font-size: 13px;
				color: #ed6a0c;
				padding-bottom: 10px;
			}

			.know {
				text-align: center;
				line-height: 40px;
				color: #1989fa;
				padding-bottom: 10px;
			}

			.content_ {
				padding: 20px;
				line-height: 24px;
				font-size: 14px;
				color: #323233;
			}

			.content_ img {
				width: 100%;
			}
		</style>
	</head>

	<body>
		<div id="app" v-cloak>
			<div class="init-full">
				<van-nav-bar class="head" title="提交订单" left-arrow @click-left="onClickLeft"></van-nav-bar>
				<div class="body-with-bottom">
					<div class="content">
						<div class="pd">
							<div class="address" @click="selectAddress_">
								<div class="a-c">
									<img src="../image/shdz.png" />
								</div>
								<div class="a-i">
									<van-cell center is-link v-if="selectAddress">
										<div>{{selectAddress.ShipTo}}&nbsp;&nbsp;{{selectAddress.TelPhone}}</div>
										<div style="color: #9e9e9e;">{{selectAddress.Address}}</div>
									</van-cell>
									<van-cell value="暂无地址可选" is-link v-if="!selectAddress" @click="selectAddress">
									</van-cell>
								</div>
							</div>

							<div class="shop">

								<div class="row flex-box" v-for="item in commodityList">
									<div class="img">
										<img :src="item.image?(shoppingMallServerIP + item.image):'../image/no.png'" />
									</div>
									<div class="flex-main desc">
										<div class="title">{{item.name}}</div>
										<div class="sku">{{item.sku}}</div>
									</div>
									<div class="price">
										<div>￥&nbsp;<span style="font-size: 15px;">{{item.price}}</span></div>
										<div style="color:#9e9e9e">x{{item.quantity}}</div>
									</div>
								</div>

								<div>
									<div class="g" v-if="gifts.length">{{giftTitle}}</div>
									<div class="row flex-box" v-for="item in gifts">
										<div class="img">
											<img
												:src="item.ThumbnailUrl180?(shoppingMallServerIP + item.ThumbnailUrl180):'../image/no.png'" />
										</div>
										<div class="flex-main desc">
											<div class="title">{{item.Name}}</div>
											<!-- <div class="sku">{{item.sku}}</div> -->
										</div>
										<div class="price">
											<div style="color:#9e9e9e">x1</div>
										</div>
									</div>
								</div>


								<div>
									<van-cell-group>
										<van-cell title="订单金额" :value="'￥' + getTotalPrice()"></van-cell>
										<van-cell title="运费" :value="freight == 0?'包邮':'￥' + freight"></van-cell>
										<van-field label="订单备注" v-model="remark" placeholder="请输入订单备注"></van-field>
										<van-cell title="支付途径">
											<div>
												<van-radio-group v-model="payChannel" checked-color="#cd1b21">
													<van-radio name="0">线上支付</van-radio>
													<van-radio name="1">线下支付</van-radio>
												</van-radio-group>
											</div>
										</van-cell>
									</van-cell-group>
								</div>
							</div>
						</div>
					</div>
					<van-loading v-if="showLoading"></van-loading>
				</div>
				<div class="bottom">
					<van-submit-bar :price="getTotal()" :loading="ifConfirm" @submit="onSubmit" button-text="提交订单">
						<span slot="tip" v-if="userInfo && userInfo.IsArrears">
							您是尊贵的尊享会员,当前可透支额度为￥{{userInfo.Quota}}
						</span>
					</van-submit-bar>
				</div>
			</div>
			<van-action-sheet v-model="showPageType" :actions="pageTypes" description="支付方式选择"
				@cancel="showPageType = false;" @select="payMoney" @click-overlay="refreshOrder"></van-action-sheet>


			<van-popup v-model="isPayByCode" :style="{ width: '90%' }" round @click-overlay="payByCodeSuccess">
				<div class="content_">
					<div class="sub_" style="text-align: center;padding-bottom: 10px;">请用微信扫描以下二维码进行付款</div>
					<img :src="payImg" />
				</div>
				<div class="know" @click="payByCodeSuccess">支付完成</div>
			</van-popup>
		</div>
	</body>

	<!-- 调用 uniapp webview 的 api ，记得需要写在 body 标签下面 -->
	<script src="../../../assets/script/uni.webview.1.5.4.js"></script>
	<script type="text/javascript">
		var vm;
		//$('.init-full').show();

		var commodityList = window.localStorage.getItem('commodityList') ? JSON.parse(window.localStorage.getItem(
			'commodityList')) : [];
		var formType = window.localStorage.getItem('formType') ? window.localStorage.getItem('formType') : '商品详情';

		var OrderNo = '';

		// var aliPayPlus = api.require('aliPayPlus');
		// var wxPay = api.require('wxPay');

		// api.addEventListener({
		// 	name: 'changeAddress'
		// }, function(ret, err) {
		// 	vm.selectAddress = ret.value.data;
		// 	vm.getComputedFreight();
		// 	vm.getDefualtAreaText();
		// });

		// api.addEventListener({
		// 	name: 'refreshBalance'
		// }, function(ret, err) {
		// 	vm.refreshBalance();
		// });

		vm = new Vue({
			el: '#app',
			data: {
				showLoading: false,
				ifConfirm: false,
				showPageType: false,
				userInfo: FLD.getUserInfo(),
				serverIP: 'http://' + FLD.serverIP,
				payImg: '',
				isPayByCode: false,
				pageTypes: [{
					name: '支付宝'
				}, {
					name: '微信'
				}, {
					name: '余额支付',
					subname: '',
					className: ''
				}, {
					name: '微信二维码支付'
				}],
				shoppingMallServerIP: 'http://' + FLD.shoppingMallServerIP,
				selectAddress: {},
				remark: '',
				freight: 0,
				shippingRegion: '',
				payChannel: '0',
				commodityList: commodityList,
				giftTitle: '',
				gifts: []
			},
			created: function() {
				var that = this;
				if (window.localStorage.getItem('addressInfo')) {
					that.selectAddress = JSON.parse(window.localStorage.getItem('addressInfo'))
				} else {
					that.getAddressList();
				}
				that.getActivity();
			},
			methods: {
				getActivity() {
					var that = this;
					var productIds = [];
					var quantitys = [];
					for (var i in that.commodityList) {
						productIds.push(that.commodityList[i].productId);
						quantitys.push(that.commodityList[i].quantity);
					}
					var obj = {
						productIds: productIds.join(),
						quantitys: quantitys.join()
					}
					console.log(JSON.stringify(obj))
					FLD.nativeRequest_shop('triggerActivity', obj, function(res) {
						console.log(JSON.stringify(res))
						that.giftTitle = res[0].promotionName;
						that.gifts = res[0].giftDt.ds;
					})
				},
				refreshBalance() {
					var that = this;
					FLD.ajax('sp_getMemberInfo', {}, function(res) {
						window.localStorage.setItem('userInfo', JSON.stringify(res.ds[0]));
						that.userInfo = res.ds[0];
					})
				},
				getAddressList() {
					var that = this;
					that.showLoading = true;
					FLD.ajax('sp_getShipAddress', {}, function(res) {
						that.showLoading = false;
						var x = -1;
						for (var i in res.ds) {
							if (res.ds[i].IsDefault) {
								x = i;
							}
						}
						if (x == -1) {
							if (res.ds.length) {
								that.selectAddress = res.ds[0];
								that.getComputedFreight();
								that.getDefualtAreaText();
							}
						} else {
							that.selectAddress = res.ds[x];
							that.getComputedFreight();
							that.getDefualtAreaText();
						}
					})
				},
				getDefualtAreaText() {
					var that = this;
					var texts = [];
					var fullregionpath = that.selectAddress.FullRegionPath.split(',');
					FLD.ajax('sp_getRegion', {
						parentRegionId: 0
					}, function(res) {
						var row1 = res.ds.filter(function(item) {
							return item.RegionId == parseInt(fullregionpath[0]);
						})
						if (row1.length) {
							texts.push(row1[0].RegionName);
						}

						FLD.ajax('sp_getRegion', {
							parentRegionId: row1[0].RegionId
						}, function(res) {
							var row2 = res.ds.filter(function(item) {
								return item.RegionId == parseInt(fullregionpath[1]);
							})
							if (row2.length) {
								texts.push(row2[0].RegionName);
							}
							FLD.ajax('sp_getRegion', {
								parentRegionId: row2[0].RegionId
							}, function(res) {
								var row3 = res.ds.filter(function(item) {
									return item.RegionId == parseInt(
										fullregionpath[2]);
								})
								if (row3.length) {
									texts.push(row3[0].RegionName);
								}
								that.shippingRegion = texts.join();
							})
						})
					})
				},
				getComputedFreight() {
					var that = this;
					var skuIds = [];
					var quantitys = [];
					for (var i in that.commodityList) {
						skuIds.push(that.commodityList[i].skuId);
						quantitys.push(that.commodityList[i].quantity);
					}
					var obj = {
						skuIds: skuIds.join(),
						quantitys: quantitys.join(),
						regionId: that.selectAddress.RegionId
					}
					FLD.shoppingMallAjax('GetFreight', obj, function(res) {
						console.log(JSON.stringify(res))
						// alert(res)
						that.freight = parseFloat(res).toFixed(2);
					})
				},
				selectAddress_() {
					var that = this;

					window.localStorage.setItem('AddressType', 'order');
					window.location.href = './addressList.html'

					// api.openWin({
					// 	name: 'addressList',
					// 	url: 'addressList.html',
					// 	reload: true,
					// 	slidBackEnabled: false,
					// 	pageParam: {
					// 		type: 'order'
					// 	}
					// })
				},
				toPay() {
					api.openWin({
						name: 'pay',
						url: 'common/pay.html',
						reload: true,
						slidBackEnabled: false
					})
				},
				getTotalPrice() {
					var that = this;
					var t = 0;
					for (var i in that.commodityList) {
						t += that.commodityList[i].price * that.commodityList[i].quantity;
					}
					return t.toFixed(2);
				},
				getTotal() {
					var that = this;
					var t = 0;
					for (var i in that.commodityList) {
						t += that.commodityList[i].price * that.commodityList[i].quantity;
					}
					return parseInt((t + parseFloat(that.freight)) * 100);

				},
				onSubmit() {
					var that = this;
					if (OrderNo) {
						that.ifConfirm = true;
						FLD.ajax('sp_getMemberInfo', {}, function(res) {
							that.ifConfirm = false;
							window.localStorage.setItem('userInfo', JSON.stringify(res.ds[0]));
							that.pageTypes[2].subname = '当前余额￥' + FLD.getUserInfo().Balance;
							that.pageTypes[2].className = (FLD.getUserInfo().Balance + FLD
								.getUserInfo().Quota - (that.getTotal()) / 100) < 0 ? 'red' : ''
							that.showPageType = true;
						})

						return false;
					}
					if (!that.selectAddress) {
						layer.open({
							content: '请选择收货地址!',
							skin: 'msg',
							time: 2
						});
						return false;
					}


					that.$dialog.confirm({
						title: '提示',
						message: '您当前选择的是' + (that.payChannel == '0' ? '线上支付' : '线下支付') + ',是否提交该订单?'
					}).then(() => {
						that.ifConfirm = true;

						FLD.ajax('sp_getMemberInfo', {}, function(res) {
							window.localStorage.setItem('userInfo', JSON.stringify(res.ds[
								0]));
							that.pageTypes[2].subname = '当前余额￥' + FLD.getUserInfo().Balance
							that.pageTypes[2].className = (FLD.getUserInfo().Balance + FLD
									.getUserInfo().Quota - (that.getTotal()) / 100) < 0 ?
								'red' : '';
							var productIds = [];
							var quantitys = [];
							for (var i in that.commodityList) {
								productIds.push(that.commodityList[i].productId);
								quantitys.push(that.commodityList[i].quantity);
							}
							var obj = {
								remark: that.remark,
								userName: FLD.getUserInfo().UserName,
								shippingRegion: that.shippingRegion,
								address: that.selectAddress.Address,
								shipTo: that.selectAddress.ShipTo,
								telphone: that.selectAddress.TelPhone,
								cellPhone: that.selectAddress.CellPhone,
								shipToDate: '时间不限',
								regionId: that.selectAddress.RegionId,
								freight: that.freight,
								fullRegionPath: that.selectAddress.FullRegionPath,
								shippingId: that.selectAddress.ShippingId,
								productIds: productIds.join(),
								quantitys: quantitys.join(),
								paymentTypeId: that.payChannel
							}
							FLD.nativeRequest_shop('createOrder', obj, function(res) {
								that.ifConfirm = false;
								OrderNo = res;
								if (that.payChannel == '0') {
									that.showPageType = true;

								} else {

									window.location.href = 'orderDetail.html';
									window.localStorage.setItem('OrderId', OrderNo);
									// window.localStorage.setItem('orderIndex', vm.filter.orderStatus);
									// api.openWin({
									// 	name: 'orderDetail',
									// 	url: 'orderDetail.html',
									// 	reload: true,
									// 	slidBackEnabled: false,
									// 	pageParam: {
									// 		OrderId: OrderNo
									// 	}
									// })

								}
								FLD.ajax('sp_deleteShipMart', {
									productIds: productIds.join()
								}, function(res) {
									api.sendEvent({
										name: 'refreshCart'
									});
								})

							})
						})


					}).catch(() => {

					});

				},
				payMoney(item, index) {
					var that = this;
					that.showPageType = false;
					if (index == 0) {

						that.ifConfirm = true;
						var obj = {
							orderNo: OrderNo,
							PayType: 1
						}
						FLD.nativeRequest_shopPay('pay', obj, function(res) {
							that.ifConfirm = false;
							aliPayPlus.payOrder({
								orderInfo: res
							}, function(ret, err) {

								window.location.href = 'orderDetail.html';
								window.localStorage.setItem('OrderId', OrderNo);
								// window.localStorage.setItem('orderIndex', vm.filter.orderStatus);
								// api.openWin({
								// 	name: 'orderDetail',
								// 	url: 'orderDetail.html',
								// 	reload: true,
								// 	slidBackEnabled: false,
								// 	pageParam: {
								// 		OrderId: OrderNo
								// 	}
								// })
							});
						})
					} else if (index == 1) {
						that.ifConfirm = true;
						var obj = {
							orderNo: OrderNo,
							PayType: 2
						}
						FLD.nativeRequest_shopPay('pay', obj, function(res) {
							that.ifConfirm = false;
							var data = JSON.parse(res);
							var myDate = new Date();
							var now = Date.parse(new Date()) / 1000;

							var stringA = 'appid=' + data.appid + '&noncestr=' + data.nonce_str +
								'&package=Sign=WXPay' + '&partnerid=' + data.mch_id + '&prepayid=' +
								data.prepay_id + '&timestamp=' + now +
								'&key=fldabcdefg123456789erfgiht56jh9f';
							var signature = api.require('signature');
							signature.md5({
								data: stringA
							}, function(ret, err) {
								if (ret.status) {
									var sign = ret.value.toUpperCase();
									wxPay.payOrder({
										apiKey: data.appid,
										orderId: data.prepay_id,
										mchId: data.mch_id,
										nonceStr: data.nonce_str,
										timeStamp: now,
										package: 'Sign=WXPay',
										sign: sign
									}, function(ret, err) {

										window.location.href = 'orderDetail.html';
										window.localStorage.setItem('OrderId', OrderNo);
										// window.localStorage.setItem('orderIndex', vm.filter.orderStatus);
										// api.openWin({
										// 	name: 'orderDetail',
										// 	url: 'orderDetail.html',
										// 	reload: true,
										// 	slidBackEnabled: false,
										// 	pageParam: {
										// 		OrderId: OrderNo
										// 	}
										// })
									});

								}
							});


						})
					} else if (index == 2) {


						if (that.pageTypes[2].className) {
							api.openWin({
								name: 'rechargeBalance',
								url: 'rechargeBalance.html',
								reload: true,
								slidBackEnabled: false
							})
						} else {
							that.ifConfirm = true;
							var obj = {
								orderId: OrderNo
							}
							FLD.ajax('sp_balanceOrderPayFinish', obj, function(res) {
								that.ifConfirm = false;
								if (res.ds && res.ds[0] && res.ds[0].status == 500) {
									layer.open({
										content: res.ds[0].msg,
										skin: 'msg',
										time: 2
									});
								} else {

									window.location.href = 'orderDetail.html';
									window.localStorage.setItem('OrderId', OrderNo);
									// window.localStorage.setItem('orderIndex', vm.filter.orderStatus);
									// api.openWin({
									// 	name: 'orderDetail',
									// 	url: 'orderDetail.html',
									// 	reload: true,
									// 	slidBackEnabled: false,
									// 	pageParam: {
									// 		OrderId: OrderNo
									// 	}
									// })
								}
							})
						}

					} else {
						var obj = {
							orderNo: OrderNo,
							PayType: 3
						}
						FLD.nativeRequest_shopPay('pay', obj, function(res) {
							that.payImg = 'data:image/png;base64,' + res;
							that.isPayByCode = true;
						})
					}
				},
				payByCodeSuccess() {
					var that = this;
					that.isPayByCode = false;

					window.location.href = 'orderDetail.html';
					window.localStorage.setItem('OrderId', OrderNo);
					// window.localStorage.setItem('orderIndex', vm.filter.orderStatus);
					// api.openWin({
					// 	name: 'orderDetail',
					// 	url: 'orderDetail.html',
					// 	reload: true,
					// 	slidBackEnabled: false,
					// 	pageParam: {
					// 		OrderId: OrderNo
					// 	}
					// })
				},
				refreshOrder() {
					var that = this;
					//关闭支付方式选择刷新订单
					window.location.href = 'orderDetail.html';
					window.localStorage.setItem('OrderId', OrderNo);
					// window.localStorage.setItem('orderIndex', vm.filter.orderStatus);
					// api.openWin({
					// 	name: 'orderDetail',
					// 	url: 'orderDetail.html',
					// 	reload: true,
					// 	slidBackEnabled: false,
					// 	pageParam: {
					// 		OrderId: OrderNo
					// 	}
					// })
				},
				onClickLeft() {
					window.history.back()
					window.localStorage.removeItem('formType')
					window.localStorage.removeItem('commodityList')
				}
			}
		})
	</script>

</html>